// 业务上格式化工具
import { unitMap } from '@/config';

/**
 * 格式化时间
 * @param {string} hex 十六进制字符串
 * @returns {string} 格式化后的时间
 */
export const formateDateTimeNew = (hex: string | number) => {
  const dt = hex
    .toString(16)
    .toUpperCase()
    .padStart(14, '0')
    .match(/.{1,2}/g)
    ?.reverse();
  if (!dt) return '-';
  const year = parseInt(dt.slice(0, 2).reverse().join(''), 16);
  const month = parseInt(dt.slice(2, 3).join(''), 16).toString().padStart(2, '0');
  const day = parseInt(dt.slice(3, 4).join(''), 16).toString().padStart(2, '0');
  const hour = parseInt(dt.slice(4, 5).join(''), 16).toString().padStart(2, '0');
  const min = parseInt(dt.slice(5, 6).join(''), 16).toString().padStart(2, '0');
  const sec = parseInt(dt.slice(6, 7).join(''), 16).toString().padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${min}:${sec}`;
};

/**
 * 将 YYYYMMDDHHMMSS 格式的字符串转换为 YYYY-MM-DD HH:MM:SS 格式的字符串
 * @param {string} str - YYYYMMDDHHMMSS.
 * @returns {string} YYYY-MM-DD HH:MM:SS.
 */

export const formateYYYYMMDDHHMMss = (str: string) => {
  const year = str.slice(0, 4);
  const month = str.slice(4, 6);
  const day = str.slice(6, 8);
  const hour = str.slice(8, 10);
  const min = str.slice(10, 12);
  const sec = str.slice(12, 14);
  return `${year}-${month}-${day} ${hour}:${min}:${sec}`;
}

/**
 * 使用提供的 map 将十六进制数据格式化为单位
 */
export const formatUnit = (data: string | number | undefined, map: Record<string, string> = unitMap) => {
  if (data === undefined) return '';
  if (typeof data === 'number') data = data.toString(16).padStart(2, '0').toUpperCase();
  const unitHex = '0x' + data;
  return map[unitHex as keyof typeof map];
};

export const formatNumber2String = (data: number) => {
  return data.toString();
}

export const formatString2Number = (data: string) => {
  return Number(data);
}

export const formatVersion = (data: string) => {
  if (!data) return '';
  const hex = Number(data).toString(16);
  if (hex === 'ffffffff') return '';
  console.log(data, hex);

  const res = `${+hex.slice(0,2)}.${+hex.slice(2,4)}.${+hex.slice(4,6)}.${+hex.slice(6,8)}`;


  return res;
}
